<!-- 问卷管理 -->
<template>
  <a-card :bordered="false" class="br-10">
    <div class="table-page-search">
      <a-form>
        <a-form-item label="问卷标题:">
          <a-input v-model="queryParam.keyWord" placeholder="搜索问卷标题" />
        </a-form-item>
        <a-form-item label="状态:">
          <a-select v-model="queryParam.status">
            <a-select-option :value="''">全部</a-select-option>
            <a-select-option :value="1">开启</a-select-option>
            <a-select-option :value="0">关闭</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="创建时间:">
          <a-range-picker v-model:value="date" valueFormat="YYYY-MM-DD" class="width-25" />
        </a-form-item>
        <span class="search-submitButtons">
          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          <a-button
            @click="
              () => {
                queryParam = { keyWord: '', status: '', startTime: '', endTime: '' }
                range = null
              }
            "
          >
            重置
          </a-button>
        </span>
      </a-form>
    </div>
    <div v-has="'operations:questionnaire:add'" class="table-operator">
      <a-button type="primary" @click="handleAdd">创建问卷</a-button>
    </div>
    <s-table
      size="default"
      ref="table"
      rowKey="userId, title"
      :rowSelection="null"
      :columns="columns"
      :data="loadData"
      :rangPicker="range"
    >
      <!-- 序号 -->
      <span slot="serial" slot-scope="text, record, index">
        {{ (pagination.current - 1) * pagination.pageSize + parseInt(index) + 1 }}
      </span>
      <!-- 封面图 -->
      <span slot="coverUrl" slot-scope="text">
        <img style="height: 60px; width: 80px; cursor: pointer" :src="text" alt="" />
      </span>
      <!-- 活动状态 -->
      <span slot="status" slot-scope="text">
        {{ text === 1 ? '开启' : '关闭' }}
      </span>
      <span slot="action" slot-scope="text, record">
        <ButtonGroup ::max-length="2">
          <a-button
            v-for="item in _btnList(record)"
            :key="item.text"
            :type="item.type"
            :ghost="item.ghost"
            size="small"
            class="width-9"
            @click="item.fn"
          >
            {{ item.text }}
          </a-button>
        </ButtonGroup>
      </span>
    </s-table>
    <index-form ref="problemForm" @add="$refs.table.refresh(true)" @upd="$refs.table.refresh()" />
    <result-module ref="resultModule" />
    <MemberChoose ref="memberChoose" @add="$refs.table.refresh(true)" @confirmUser="sendMessage" />
  </a-card>
</template>

<script>
import { STable } from '@/components'
import { memberLevelGetDownList } from '@/api/system/system'
import { questionList, updateStatus, send, qrCode } from '@/api/operations/questionnaire'
import indexForm from './indexForm'
import resultModule from './resultModule.vue'
import MemberChoose from '@/components/MemberChoose/indexs.vue'
import { checkPermission } from '@/utils/authority.js'
import ButtonGroup from '@/components/Table/buttonGroup'

export default {
  name: 'questionnaire',
  components: {
    STable,
    indexForm,
    resultModule,
    MemberChoose,
    ButtonGroup
  },
  data() {
    return {
      selectNum: '',
      pagination: {
        current: 1,
        pageSize: 10
      },
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 查询参数
      queryParam: {
        keyWord: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      // 活动表单
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          width: '80px'
        },
        {
          title: '问卷标题',
          dataIndex: 'title',
          ellipsis: true
        },
        {
          title: '问题数量',
          dataIndex: 'questionNum',
          ellipsis: true
        },
        {
          title: '状态',
          dataIndex: 'status',
          ellipsis: true,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '填写人数',
          dataIndex: 'userAnswerNum',
          ellipsis: true
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true
        },
        {
          title: '问卷结束时间',
          dataIndex: 'endTime',
          ellipsis: true
        },
        {
          title: '操作',
          width: '270px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],

      range: null,
      pageNum: 1,
      pages: 1,
      pageSize: 10,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return questionList(Object.assign(parameter, this.queryParam))
      },

      selectedRows: [],
      drd: {
        member_level_list: []
      },
      questionnaireId: undefined
    }
  },
  computed: {
    date: {
      get() {
        return [this.queryParam.startTime, this.queryParam.endTime]
      },
      set(val) {
        this.queryParam.startTime = val[0]
        this.queryParam.endTime = val[1]
      }
    }
  },
  created() {
    this.getMemberLevelGetDownList()
  },
  methods: {
    async getQrCode(id) {
      let { code, data, msg } = await qrCode(id)
      if (code != 0) return this.$message.error(msg)
      window.open(data, '_self')
    },
    handleOk() {
      this.$refs.table.refresh(true)
    },
    handleReload() {
      this.$refs.table.refresh()
    },
    // 问卷新增
    handleAdd() {
      var obj = {}
      var params = {
        title: '创建问卷',
        type: 'add',
        data: obj
      }
      this.$refs.problemForm.add(params)
    },
    //显示问卷详情
    handleShowDetail(record, type) {
      var obj = JSON.parse(JSON.stringify(record))
      // if (record.politicalTitle) {
      //   obj.politicalTitle = record.politicalTitle.split(',')
      // } else {
      //   obj.politicalTitle = undefined
      // }
      var params = {
        title: type === 'edit' ? '问卷详情' : '问卷复制',
        type,
        data: obj
      }
      this.$refs.problemForm.edit(params)
    },
    //开启、关闭问卷
    handleUpdateStatus(id, status) {
      var _this = this
      let status_text = status === 1 ? '关闭' : '开启'
      this.$confirm({
        title: `${status_text}问卷?`,
        content: `是否确定${status_text}该问卷?`,
        onOk() {
          updateStatus({ id, status: status === 1 ? 0 : 1 }).then(res => {
            if (res.code === 0) {
              _this.$message.success(`${status_text}成功`)
              _this.handleReload()
            } else {
              _this.$message.error(res.msg)
            }
          })
        },
        onCancel() {}
      })
    },
    // handleCopyAndCreate(record) {
    //   var obj = JSON.parse(JSON.stringify(record))
    //   var params = {
    //     title: '问卷复制',
    //     type: 'copy',
    //     data: obj
    //   }
    //   this.$refs.problemForm.edit(params)
    // },
    async getMemberLevelGetDownList() {
      let res = await memberLevelGetDownList()
      this.drd.member_level_list = res.data || []
    },
    //显示调查结果
    handleShowResult(id) {
      this.$refs.resultModule.moduleShow(id)
    },
    //发送推送消息
    async sendMessage(rows) {
      // if (!rows || !rows.length) return this.$message.error('请选择推送人员')
      // let { code, msg } = await send({ id: this.questionnaireId, leadingIds: rows.map(item => item.leadingId) })
      // this.$message[code === 0 ? 'success' : 'error'](msg)
      if (!rows || !rows.length) return this.$message.error('请选择推送人员')
      let { code, msg } = await send({ id: this.questionnaireId, memberList: rows.map(item => item) })
      this.$message[code === 0 ? 'success' : 'error'](msg)
      this.selectNum = rows
    },
    handleShowMember(id) {
      this.questionnaireId = id
      this.$refs.memberChoose.moduleShow(undefined, this.selectNum)
    },
    _btnList(record) {
      let oldList = [
        {
          show: checkPermission('operations:questionnaire:detail'),
          text: '详情',
          fn: () => this.handleShowDetail(record, 'edit'),
        },
        {
          show: checkPermission('operations:questionnaire:result'),
          text: '调查结果',
          type: 'primary',
          ghost: true,
          fn: () => this.handleShowResult(record.questionnaireId),
        },
        {
          show: checkPermission('operations:questionnaire:status'),
          text: `${record.status === 1 ? '关闭' : '开启'}`,
          type: `${record.status === 1 ? 'danger' : 'primary'}`,
          ghost: true,
          fn: () => this.handleUpdateStatus(record.questionnaireId, record.status),
        },
        {
          show: checkPermission('operations:questionnaire:add'),
          text: '复制并创建',
          type: 'primary',
          ghost: true,
          fn: () => this.handleShowDetail(record, 'copy'),
        },
        {
          show: checkPermission('operations:questionnaire:selectUser'),
          text: '发送人员',
          type: 'primary',
          ghost: true,
          fn: () => this.handleShowMember(record.questionnaireId),
        },
        {
          show: checkPermission('operations:questionnaire:dwCode'),
          text: '下载二维码',
          type: 'primary',
          ghost: true,
          fn: () => this.getQrCode(record.questionnaireId),
        }
      ]
      return oldList.filter((v) => v.show)
    },
  },
  provide() {
    return {
      drd: () => this.drd
    }
  }
}
</script>
<style scoped lang="less">
</style>
